<template>
	<view>
		<view class="status_bar">
			<!-- 这里是状态栏 -->
		</view>
		<view class="container">
			<!-- 头部-->
			<view class="carousel-section">
				<!-- 背景色区域 -->
				<view class="titleNview-background"
					style="background: url('../../static/wximg/bjTop2.png'); background-size: 100%;">
				</view>
				<view class="content" :style="{height: heightContent +'px'}">
					<view class="title-logo">
						<image src="../../static/wximg/ycLogo.png"></image>
					</view>
					<view class="login">
						<view class="txtLogin">
							<input type="number" v-model="form.username" class="input-text" placeholder="请输入手机号码" />
						</view>
						<view class="txtLogin">
							<input type="password" v-model="form.password" class="input-text" placeholder="请输入密码" />
						</view>
						<view class="item-sm  wos-flex wos-flex-row wos-flex-between">
							<view class="item-sm-title">
								<view v-if="ifData">
									使用数据网络
								</view>
								<view v-else>
									使用物联网数据
								</view>
							</view>
							<view>
								<view v-if="ifData">
									<switch color="#007457" style="transform: scale(0.7);" checked @change="switch1Change" />
								</view>
								<view v-else>
									<switch color="#007457" style="transform: scale(0.7);" @change="switch1Change" />
								</view>
							</view>
						</view>
						<button class="wxq-btn loginWx" v-on:click="Login">登录</button>
						<!-- <button class="wxq-btn goback" v-on:click="opentyx">取消登录</button> -->
						<button open-type=""></button>
						<text style="color:#999; display: block; text-align: center;">仅供长春烟草内部人员使用</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>
<script>
	import config from '@/api/config.js';
	import service from '../../service.js';
	import {
		loginWx
	} from '@/api/request.js';
	import url from '@/api/url.js';
	const environment = uni.getSystemInfoSync().environment;
	import {
		// mapState,  
		mapMutations
	} from 'vuex';
	export default {
		computed: {},
		data() {
			return {
				//获取白色背景高度
				ifData: true,
				heightContent: '',
				url: url,
				code: '', //微信临时登录凭证
				scrollTop: 0,
				old: {
					scrollTop: 0
				},
				form: {
					username: "", // 13166803270
					password: "" // 123456
				},
			}
		},
		onLoad: function() {
			this.ifData = uni.getStorageSync('netType')
			let user = service.getUsers()
			if (user.user != undefined) {
				uni.reLaunch({
					url: '/pages/index/index'
				})
				return;
			}
		},
		methods: {
			switch1Change(e) {
				this.ifData = e.target.value
				// console.log(e.target.value)
				uni.setStorageSync('netType', e.target.value)
			},
			async Login() {
				let res = await loginWx(this.form)

				if (res.code == 200) {

					if (res.map.data === '手机号或密码错误') {
						uni.showModal({
							title: '警告',
							content: '手机号或密码错误,无法登录!',
							showCancel: false
						})
						return false
					}
					if (res.map != null) {
						if (res.map.data == null) {
							uni.showModal({
								title: '警告',
								content: '您非本公司员工或未绑定,无法登录!',
								showCancel: false
							})
						} else {
							if (res.map.data.customerShop != null) {
								if (res.map.data.customerShop.id == "") { //防止漏网之鱼
									uni.showModal({
										title: '警告',
										content: '您与商家未被绑定,请绑定商家在登录!',
										showCancel: false
									})
									return;
								}
							}
							service.addUser(res.map.data);
							uni.switchTab({
								url: '/pages/index/index'
							})
						}
					} else {
						uni.showModal({
							title: '警告',
							content: '您非本公司员工或未绑定,无法登录!',
							showCancel: false
						})
					}
				} else {
					uni.showModal({
						title: '警告',
						content: 'code不符 请联系管理员',
						showCancel: false
					})
				}
			},
			GetUserInfo(e) {


				var that = this;
				uni.getUserProfile({
					desc: '用于完善用户资料',
					lang: 'zh_CN',
					success: function(res) {

						/* console.log( 'wx.getUserProfile=>用户允许了授权' );  
						 console.log( res.userInfo );  
						 console.log( res.rawData );  
						 console.log( res.signature );  
						 console.log( res.encryptedData );  
						 console.log( res.iv );  
						 console.log( res.cloudID );  */

						/* 以下是网友说的，我还没来得及测试：  
						按新方案的意思，encryptedData，iv，rawData，signature这几个属性用不上了。  
						小程序端wx.getUserProfile()获取到userInfo，wx.login()获取到code，  
						这两个传给后端，code通过code2session接口获取到unionid，openid，session_key等；  
						原有的拿session_key解密encryptedData的逻辑不需要了，毕竟encryptedData也只是比userInfo多了openid和unionid。  
						*/

					},
					fail: function(res) {
						console.log('wx.getUserProfile=>用户拒绝了授权');
						console.log(res);

					},
				});


			},



			//微信授权登录
			getUserInfo(e) {
				//关闭弹窗方法
				let qxPop = this.$refs.qxPop
				qxPop.onTap()
				//登录
				let that = this;
				let eData = JSON.parse(e.detail.rawData);
				if (environment == "wxwork") { //企业微信

					let access_token = "";
					let expires_in = 0; //有效时间秒

					uni.request({ //请求获取 access_token
						url: url() + '/app/getEnAccessToken',
						success: codeRes => {

							if (codeRes.data.errcode == 0) {

								console.log("获取access_token成功")

								access_token = codeRes.data.access_token
								expires_in = codeRes.data.expires_in

								wx.qy.login({
									success: (res) => {
										if (res.code) {

											uni.request({
												url: url() + '/app/getEnOpenId?token=' +
													access_token +
													'&code=' + res.code,
												success: codeRes => {
													if (codeRes.data.errcode == 0) {
														// console.log("获取userid成功",codeRes.data.userid) 
														let data = {
															"wx": {
																userid: codeRes
																	.data.userid,
																session_key: codeRes
																	.data
																	.session_key,
																corpid: codeRes
																	.data.corpid,
																access_token: access_token,
																expires_in: expires_in,
																eData: eData,
															}
														}
														service.addWxinfo(data);

														//这里开始接入后台登录
														let param = {
															wx_userid: codeRes.data
																.userid
														};
														loginWx(param).then(res => {

															if (res.code ==
																200) {

																if (res.map !=
																	null) {

																	if (res.map
																		.data ==
																		null) {

																		uni.showModal({
																			title: '警告',
																			content: '您非本公司员工或未绑定,无法登录!',
																			showCancel: false
																		})
																	} else {

																		if (res
																			.map
																			.data
																			.customerShop !=
																			null
																		) {

																			if (res
																				.map
																				.data
																				.customerShop
																				.id ==
																				""
																			) { //防止漏网之鱼
																				uni.showModal({
																					title: '警告',
																					content: '您与商家未被绑定,请绑定商家在登录!',
																					showCancel: false
																				})
																				return;
																			}
																		}
																		service
																			.addUser(
																				res
																				.map
																				.data
																			);
																		uni.switchTab({
																			url: '/pages/index/index'
																		})
																	}
																} else {
																	uni.showModal({
																		title: '警告',
																		content: '您非本公司员工或未绑定,无法登录!',
																		showCancel: false
																	})
																}
															} else {
																uni.showModal({
																	title: '警告',
																	content: 'code不符 请联系管理员',
																	showCancel: false
																})
															}
														}).catch(err => {
															console.log(err);
															uni.showModal({
																title: '警告',
																content: '失败',
																showCancel: false
															})
														})

													} else {
														console.log("获取userid错误")
														console.log(codeRes);
													}
												},
												fail: () => {
													uni.showToast({
														title: '获取  企业 userid 失败',
														icon: 'none'
													});
													return false;
												}
											});

										} else {
											uni.showToast({
												title: '企业微信系统异常，请联系管理员!'
											})
										}
									}
								})

							} else {
								console.log("获取access_token错误")
								console.log(codeRes);
							}
						},
						fail: () => {
							uni.showToast({
								title: '获取 企业微信 access_token失败',
								icon: 'none'
							});
							return false;
						}
					});
				} else { //微信获取
					let p = this.getSetting();
					p.then(function(isAuth) {
						console.log('是否已经授权', isAuth);
						if (isAuth) {
							wx.login({
								success: (res) => {
									if (res.errMsg == "login:ok") {
										uni.request({
											url: url() + '/app/getOpenId?code=' + res.code,
											success: codeRes => {
												that.sessionKey = codeRes.data.session_key;
												console.log(codeRes);
												let data = {
													"wx": {
														openid: codeRes.data.openid,
														session_key: codeRes.data
															.session_key,
														eData: eData,
													}
												}
												service.addWxinfo(data);
												//这里开始接入后台登录
												let param = {
													wx_openid: codeRes.data.openid
												};
												console.log(param);
												loginWx(param).then(res => {
													if (res.code == 200) {
														if (res.map != null) {
															if (res.map.data ==
																null) {
																uni.showModal({
																	title: '警告',
																	content: '您不是本公司员工无法登录!',
																	showCancel: false
																})
															} else {
																service.addUser(res
																	.map.data);
																uni.switchTab({
																	url: '/pages/index/index'
																})
															}
														} else {
															uni.showModal({
																title: '警告',
																content: '您未被本公司授权 无法登录!',
																showCancel: false
															})
														}

													} else {
														uni.showModal({
															title: '警告',
															content: 'code不符 请联系管理员',
															showCancel: false
														})
													}
												}).catch(err => {
													uni.showModal({
														title: '警告',
														content: '失败',
														showCancel: false
													})
												})
											},
											fail: (el) => {
												console.log(el)
												uni.showToast({
													title: JSON.stringify(el),
													icon: 'none'
												});
												return false;
											}
										});

									} else {
										uni.showToast({
											title: '小程序系统异常，请联系管理员!'
										})
									}
								}
							})
						} else {
							uni.showToast({
								title: '授权失败，请确认授权已开启',
								mask: true,
								icon: 'none'
							})
						}
					})

				}
			},
			//获取用户的当前设置
			getSetting() {
				return new Promise(function(resolve, reject) {
					wx.getSetting({
						success: function(res) {
							if (res.authSetting['scope.userInfo']) {
								console.log('存在');
								resolve(true);
							} else {
								console.log('不存在');
								resolve(false);
							}
						}
					})
				}).catch((e) => {
					console.log(e)
				});;
			},
			openqxPop() {
				let qxPop = this.$refs.qxPop
				qxPop.open()
			},
			hideqxPop() {
				let qxPop = this.$refs.qxPop
				qxPop.onTap()
			},
			queryCode() {
				console.log("获取code");
				if (environment == "wxwork") { //企业微信登录
					wx.qy.login({
						success: (res) => {
							if (res.code) {
								this.code = res.code;
							} else {
								uni.showToast({
									title: '企业微信系统异常，请联系管理员!'
								})
							}
						}
					})
				} else {
					wx.login({
						success: (res) => {
							if (res.errMsg == "login:ok") {
								this.code = res.code;
							} else {
								uni.showToast({
									title: '小程序系统异常，请联系管理员!'
								})
							}
						}
					})
				}

			}
		},

	}

	/*       // 0. 显示加载的效果
	       uni.showLoading({
	           title: '登录中...'
	       }); */

	// 1. wx 获取登录用户 code
	/*      uni.login({
	          provider: 'weixin',
	          success: loginRes => {
	              console.log(loginRes);
	              _self.code = loginRes.code;
	              // 2. 将用户登录code传递到后台置换用户SessionKey、OpenId等信息
	           
	          },
	          fail: () => {
	              uni.showToast({ title: '获取 code 失败', icon: 'none' });
	              return false;
	          }
	      }); */
</script>

<style>
	.input-text {
		border-bottom: 1rpx solid #C0C0C0;
		padding: 10rpx 0;
	}

	.status_bar {
		/* height: calc(var(--status-bar-height) + 250px); */
		width: 100%;
	}

	.content {
		position: relative;
		width: 91%;
		margin: 0 auto;
		background-color: white;
		margin-top: -120upx;
		z-index: 2;
		border-radius: 25px;
		/* 定义flex容器 */
		display: flex;
		flex: 1;
		/*设置容器内部容器的排列方向*/
		flex-direction: column;
		align-items: center;
		justify-content: center;

		padding: 100rpx 0;
	}

	.titleNview-background {
		width: 100%;
		height: 418upx;
		-webkit-transition: .4s;
		transition: .4s;
		background-size: 100% 100%;
	}

	.title-logo {
		width: 280upx;
		height: 233.33upx;
		margin-bottom: 50upx;
	}

	.title-logo image {
		width: 100%;
		height: 100%;
	}

	.login {
		width: 90%;
		position: relative;
	}

	.loginWx {
		background: #007457;
		color: #fff;
	}

	.goback {
		background: #eee;
		color: #333;
		margin-bottom: 24rpx;
	}

	.txtLogin {
		width: 500rpx;
		margin: 0 auto;
		margin-bottom: 20rpx;
	}

	.goback {
		width: 100%;
		border-radius: 200upx;
		margin: 80upx auto;
		box-shadow: 0 2px 5px #e3e3e3;
	}

	.loginWx {
		width: 100%;
		border-radius: 200upx;
		margin: 160upx auto 20upx;
		box-shadow: 0 2px 5px #e3e3e3;
	}

	/*弹窗*/
	.popup-info {
		position: fixed;
		min-width: 90%;
		max-width: 90%;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		font-size: 30upx;
		border-radius: 27upx;
		background-color: #fff;
		z-index: 9999;
		border: 1px solid #d9d9d9;
	}

	.popuptitle {
		border-top-left-radius: 27upx;
		border-top-right-radius: 27upx;
		background-color: #f9f9f9;
		border-bottom: 1px solid #d9d9d9;
		height: 98upx;
		width: 100%;
		text-align: center;
		line-height: 98upx;
		color: #333;
		font-size: 32upx;
	}

	.ui-license {
		border: 1px solid #d9d9d9;
		height: 550upx;
		margin: 8% 5% 5%;
		overflow-x: hidden;
		overflow-y: scroll !important;
		padding: 25upx 3%;
		resize: both;
		width: 84%;
	}

	.login-text {
		width: 60%;
		margin: 0 auto;
		z-index: 2;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.login-button-text {
		width: 80%;
		border-radius: 10upx;
		background-color: #ffc562 !important;
		font-size: 28upx;
		color: #fff;
		margin: 0 3% 5%;
	}

	.login-button-text::after {
		border: none;
	}
	.wos-flex {
		display: flex;
	}
	
	.wos-flex-row {
		flex-direction: row;
	}
	
	.wos-flex-column {
		flex-direction: column
	}
	
	.wos-flex-column-reverse {
		flex-direction: column-reverse
	}
	
	.wos-flex-center {
		justify-content: center;
		align-items: center
	}
	
	.wos-flex-between {
		justify-content: space-between;
	}
	
	.wos-flex-warp {
		flex-wrap: wrap
	}
	
	.wos-flex-nowrap {
		flex-wrap: nowrap;
	}
	
	.wos-flex-auto {
		/* flex: auto; */
		flex: 1
	}
	
	.wos-flex-right {
		justify-content: flex-end
	}
	.item-sm{
		width: 500rpx;
		margin: 0 auto;
		padding: 20rpx 32rpx;
	}
	
	.item-sm-title {
		padding-top: 15rpx;
	}
</style>
